<template>
  <div class="w-full">
    <el-form :model="form" label-width="120px" :label-position="'top'">
      <el-form-item label="标题">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="">

        <el-tabs v-model="activeTab" class="w-full">
          <el-tab-pane label="上传新素材" name="upload">
            <UploadFile v-model="src" title="选择素材" @fileListChange="fileListChange" />
          </el-tab-pane>
          <el-tab-pane label="素材库选择" name="second">
            <ElButton @click="resourceVisible = true">打开素材库</ElButton>
            <ResourcePicker v-model:visible="resourceVisible" multiple @confirm="confirmResource" />
          </el-tab-pane>
        </el-tabs>
        <ElCard class="w-full mt-4">
          <template #header>
            已选素材：
          </template>
          <div v-if="form.resources?.length > 0">
            <div v-for="(res, idx) in form.resources" class="flex items-center justify-between">
              <span>{{ res.origin_name }}</span>
              <span class="ml-4 cursor-pointer" @click="removeResource(idx)">
                <el-icon class="">
                  <Delete />
                </el-icon>
              </span>
            </div>
          </div>

          <div v-else>

            未选择
          </div>

        </ElCard>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang='ts'>
import UploadFile from '@/components/ma-upload-file/index.vue'
import ResourcePicker from '@/components/ma-resource-picker/index.vue'
import { Delete } from '@element-plus/icons-vue'
const activeTab = ref('upload');
const resourceVisible = ref<boolean>(false);
const model = defineModel() as any;
const src = ref();
const form = ref(model.value || {
  title: '',
  resources: []
});
watch(() => form.value, (data) => {
  model.value = data;
}, {
  immediate: true,
  deep: true
})
const formatFiles = files => files.map(file => ({
  url: file.url,
  origin_name: file.origin_name,
  suffix: file.suffix,
  mime_type: file.mime_type,
}))
const confirmResource = files => {
  form.value.resources.push(...formatFiles(files));
}
const fileListChange = (fileList) => {
  const files = fileList.map(file => toRaw(file.response.data));
  form.value.resources.push(...formatFiles(files));
}
const removeResource = (idx: number) => {
  form.value.resources.splice(idx, 1)
}
</script>

<style></style>
